package com.easyCode.mysql.sqlBuilder.sqlInfo;

import com.easyCode.mysql.constants.MysqlRowFormatTypeConstants;
import com.easyCode.sqlBuilder.sqlInfo.BaseTableSqlInfo;
import com.easyCode.sqlBuilder.sqlUtil.SqlBuildUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 负责提供构建表结构的相关sql信息
 *
 * @author 大忽悠
 * @create 2022/11/8 20:04
 */
@Data
public class MysqlTableSqlInfo extends BaseTableSqlInfo {
    /**
     * 字符集
     */
    private final CharsetSqlInfo charsetSqlInfo=CharsetSqlInfo.getDefault();
    /**
     * 行格式: 默认行格式为compact
     */
    private String rowFormat= MysqlRowFormatTypeConstants.COMPACT;

    @Override
    protected String doBuildSql() {
        return SqlBuildUtil.assembler(buildDropTableSql()
                ,buildCreateTableSql(SqlBuildUtil.assemblerWithDelimiter(buildFiledSql(),buildKeySql())));
    }

    private String buildCreateTableSql(String filedAndKeySql) {
        return SqlBuildUtil
                .buildSqlWithSemicolon("CREATE TABLE",SqlBuildUtil.wrapSqlParam(tableName),"(",filedAndKeySql,")",
                        "ENGINE=InnoDB AUTO_INCREMENT=0",charsetSqlInfo.buildSql(),"ROW_FORMAT=",rowFormat,
                        SqlBuildUtil.assembleIfNeed(comment, "COMMENT " + SqlBuildUtil.wrapSqlVal(comment)));
    }

    private String buildDropTableSql() {
        return dropTable?SqlBuildUtil.buildSqlWithSemicolon("DROP TABLE IF EXISTS",SqlBuildUtil.wrapSqlParam(tableName)):"";
    }

    /**
     * 遍历每个索引,组装得到完整索引sql语句
     */
    private String buildKeySql() {
        return SqlBuildUtil.assemblerWithDelimiter(baseKeySqlInfoList);
    }

    /**
     * 遍历每个字段信息,组装得到完成的字段sql语句
     *
     * @return
     */
    private String buildFiledSql() {
        return SqlBuildUtil.assemblerWithDelimiter(baseFiledSqlInfoList);
    }
}
